package com.lance.answer.question_export;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.MD5Utils;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.util.*;

/**
 * <p>以学生的身份获取某门课程答案<p>
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2022/4/4 14:47
 */
public class GetSingleAnswerByStudent {


    public static void main(String[] args) throws Exception {
        ChromeDriver driver = Util.getDriver(null);
        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        driver.get(url);
        Thread.sleep(2000);
//        String userName = "2051001463552";
//        String pwd = "Ouchn109900328";
//        String userName = "2111001200703";
//        String pwd = "Ouchn19980608";账号1942101405334
//密码Ouchn19880904  2113001401827
//Ouchn19770122
//        String userName = "2165001206526";
//        String pwd = "Ouchn19941025";
//        // String subjectName = "国家赔偿法";
//        String subjectName = "公司财务";

        String userName = "2165001206620";
        String pwd = "Ouchn19890506";
        // String subjectName = "国家赔偿法";
        String subjectName = "社区护理学（本）";
       // String subjectName = "商法";
        List<String> paths = new ArrayList<>();
        paths.add("http://xinjiang.ouchn.cn/mod/quiz/review.php?attempt=11979735&cmid=446117");


//        paths.add("http://xinjiang.ouchn.cn/mod/quiz/review.php?attempt=12166468&cmid=384136");
//        paths.add("http://xinjiang.ouchn.cn/mod/quiz/review.php?attempt=12166564&cmid=384136");
//        paths.add("http://xinjiang.ouchn.cn/mod/quiz/review.php?attempt=12166576&cmid=384159");
//        paths.add("http://xinjiang.ouchn.cn/mod/quiz/review.php?attempt=12166588&cmid=384159");
//        paths.add("http://xinjiang.ouchn.cn/mod/quiz/review.php?attempt=12166650&cmid=384180");
//        paths.add("http://xinjiang.ouchn.cn/mod/quiz/review.php?attempt=12166676&cmid=384195");
//        paths.add("http://xinjiang.ouchn.cn/mod/quiz/review.php?attempt=12166699&cmid=384221");


//        paths.add("http://fujian.ouchn.cn/mod/quiz/review.php?attempt=6671034&cmid=336363");
//        paths.add("http://fujian.ouchn.cn/mod/quiz/review.php?attempt=6671050&cmid=336363");
//        paths.add("http://fujian.ouchn.cn/mod/quiz/review.php?attempt=6671059&cmid=336363");
//        paths.add("http://fujian.ouchn.cn/mod/quiz/review.php?attempt=6671073&cmid=336364");
//        paths.add("http://fujian.ouchn.cn/mod/quiz/review.php?attempt=6671081&cmid=336364");
//        paths.add("http://fujian.ouchn.cn/mod/quiz/review.php?attempt=6671092&cmid=336364");
//        paths.add("http://fujian.ouchn.cn/mod/quiz/review.php?attempt=6671104&cmid=336365");
//        paths.add("http://fujian.ouchn.cn/mod/quiz/review.php?attempt=6671111&cmid=336365");
//        paths.add("http://fujian.ouchn.cn/mod/quiz/review.php?attempt=6671121&cmid=336365");



        Util.login(driver, userName, pwd);

        Thread.sleep(3000);



        for (WebElement we : driver.findElements(By.className("media-body"))) {
            Util.switchToFirst(driver);
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();

            // 2021-12-10
//            if (!mediaTitle.contains(subjectName)) {
//                continue;
//            }
            // 2021-12-10

            if (!mediaTitle.equals(subjectName)) {
                continue;
            }
            try {
                //点击进入学习的按钮
                WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
                studyButton.click();
                //Util.switchToLast(driver);
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            }
        }



        List<Question> questions = Lists.newArrayList();
        // FIXME 如果标题相同就判断不出来了
        Set<String> titleSet = Sets.newHashSet();
        for (String urlTask : paths) {
            driver.get(urlTask);
            Thread.sleep(5000);
            // Util.switchToLast(driver);
            Thread.sleep(5000);

            boolean doubleGoBack = false;

          //  for (int i = 0; i < infoList.size(); i++) {

              //  Thread.sleep(5000);
                Thread.sleep(5000);
                for (WebElement wa : driver.findElements(By.tagName("a"))) {
                    if ("在一页上显示所有试题".equals(wa.getText())) {
                        doubleGoBack = true;
                        wa.click();
                        Thread.sleep(5000);
                        break;
                    }

                }


            for (WebElement singleSubject : Util.getSinglePageQuestionList(driver)) {

                if (null == singleSubject) {
                    continue;
                }
                String answerClass = singleSubject.getAttribute("class");
                // informationitem  description description
                if (Strings.isNullOrEmpty(answerClass)) {
                    continue;
                }
                if (answerClass.contains("description") || answerClass.contains("informationitem")) {
                    continue;
                }
                Question question = new Question();
                question.setAnalyze("无");
                question.setDifficult(1);
                question.setGradeLevel(21);

                String questionId = singleSubject.getAttribute("id");
                // 这里的questionId是题目的ID
                System.err.println("questionId:" + questionId);
                WebElement contentElement = singleSubject.findElement(By.className("content"));

                WebElement hiddenElement = singleSubject.
                        findElement(By.cssSelector("input[type='hidden']"));
                // 题干
                String name = hiddenElement.getAttribute("name");
                System.err.println("name:" + name);
                // qtext
                // 题目标题
                String title = Util.getTitle(contentElement);
                question.setTitle(title);
                // FIXME
                if (titleSet.contains(title)) {
                    continue;
                }
                // 题目提示 tip prompt
                WebElement promptElement = Util.findByClassName(contentElement, "prompt");
                if (null != promptElement) {
                    System.err.println("promptElement:" + promptElement.getText());
                }

                WebElement answerElement = Util.findByClassName(contentElement, "answer");
                String labelType = "";
                List<Item> items = Lists.newArrayList();
                items.clear();
                if (null != answerElement) {
                    // 找到每一个选项
                    // 针对多选和单选和判断题
                    for (WebElement singleAnswerElement : answerElement.
                            findElements(By.cssSelector("div[class^='r0'],div[class^='r1']"))) {
                        // 答案的序号 判断题没有序号 多选和单选有序号
                        String answerNumber = "";
                        WebElement numberElement = Util.findByClassName(singleAnswerElement, "answernumber");
                        if (numberElement != null) {
                            answerNumber = numberElement.getText();
                        }
                        // 每个答案的文本 p标签 =单选和多选 label标签=判断题
                        String answerContent = Util.getAnswer(singleAnswerElement);
                        // 找到单选框或复选框
                        WebElement checkboxElement = singleAnswerElement.
                                findElement(By.cssSelector("input[type='checkbox'],input[type='radio']"));
                        labelType = checkboxElement.getAttribute("type");
                        // 这里的ID是每个选项的ID
                        // answerContent是每个选项的内容
                        Item item = new Item();
                        item.setPrefix(answerNumber);
                        item.setContent(answerContent);
                        if (Strings.isNullOrEmpty(answerContent)) {
                            item.setPrefix(answerContent);
                        }
                        items.add(item);
                    }
                }


                // 获取正确答案
                WebElement rightAnswer = Util.findByClassName(singleSubject, "rightanswer");
                if (rightAnswer != null) {
                    //     String[] correctArray = new String[]{rightAnswer.getText()};
                    String[] correctArray = new String[]{Util.getAnswer(rightAnswer)};
                    question.setCorrectArray(correctArray);
                }
                if (question.getCorrectArray() == null) {
                    rightAnswer = Util.findByClassName(singleSubject, "generalfeedback");
                    if (rightAnswer != null) {
                        //  String[] correctArray = new String[]{Util.getAnswer(rightAnswer)};
                        String[] correctArray = new String[]{rightAnswer.getText()};
                        question.setCorrectArray(correctArray);
                    }
                }

                question.setItems(items);
                titleSet.add(question.getTitle());

                answerClass = singleSubject.getAttribute("class");
                // 简单题que essay manualgraded notyetanswered
                if (answerClass.contains("essay")) {
                    // 等于选项的ID
                    question.setQuestionType(5);
                    question.setQuestionTypeDesc("简答题");
                    question.setCorrect("简单题");
                    questions.add(question);
                }
                // 判断题 que truefalse manualgraded notyetanswered  que truefalse deferredfeedback notyetanswered
                if (answerClass.contains("truefalse")) {
                    question.setQuestionType(3);
                    question.setQuestionTypeDesc("判断题");
                    questions.add(question);
                }
                // 填空题 que shortanswer deferredfeedback notyetanswered
                if (answerClass.contains("shortanswer") || answerClass.contains("multianswer")) {
                    // 等于选项的ID
                    question.setQuestionType(4);
                    question.setQuestionTypeDesc("填空题");
                    questions.add(question);
                }
                // que ddwtos deferredfeedback notyetanswered

                if (answerClass.contains("ddwtos")) {
                    // 等于选项的ID
                    question.setQuestionType(10);
                    question.setQuestionTypeDesc("ddwtos");
                    questions.add(question);
                    WebElement rightAnswer222 = Util.findByClassName(singleSubject, "rightanswer");
                    if (rightAnswer != null) {
                        //     String[] correctArray = new String[]{rightAnswer.getText()};
                        String[] correctArray = new String[]{Util.dealContent(rightAnswer222.getText())};
                        question.setCorrectArray(correctArray);
                    }
                }

                if (answerClass.contains("que match deferredfeedback") // 匹配题目
                ) {
                    // 等于选项的ID
                    WebElement tableWe = contentElement.findElement(By.cssSelector("table[class='answer']"));

                    List<Item> items1 = Lists.newArrayList();
                    for(WebElement trWe:tableWe. findElements(By.cssSelector("tr[class='r0'],tr[class='r1']"))){
                        Item item = new Item();
                        item.setContent(trWe.findElement(By.cssSelector("td[class='text']")).getText());
                        items1.add(item);
                    }
                    question.setItems(items1);
                    question.setQuestionType(61);
                    question.setQuestionTypeDesc("填空题");
                    question.setCorrect("匹配题目");
                //    question.setCorrect(contentElement.findElement(By.cssSelector("div[clas='rightanswer']")).getText());
                    questions.add(question);
                }
                // 多选|单选：que multichoice deferredfeedback notyetanswered
                if (answerClass.contains("multichoice")) {
                    if ("radio".equals(labelType)) {
                        question.setQuestionType(1);
                        question.setQuestionTypeDesc("单选题");
                        questions.add(question);
                    }
                    if ("checkbox".equals(labelType)) {
                        question.setQuestionType(2);
                        question.setQuestionTypeDesc("多选题");
                        questions.add(question);
                    }
                }

            }
//                if (i > 0) {
//                    break;
//                }
                Thread.sleep(5000);
                driver.navigate().back();
                Thread.sleep(2000);
                if (doubleGoBack) {
                    driver.navigate().back();
                    Thread.sleep(2000);
                }

            Thread.sleep(2000);
            //  driver.close();
            Util.switchToLast(driver);
            Thread.sleep(2000);

        }

        Collections.sort(questions);
        List<Map<String, Object>> answers = new ArrayList<>();
        for (Question question : questions) {

            String title = question.getTitle();
            title = Util.dealContent(title);

            Map<String, Object> answerMap = new HashMap<>();
            answerMap.put("questionType", question.getQuestionType());
            answerMap.put("answerType", "click");
            answerMap.put("questionTypeDesc", question.getQuestionTypeDesc());
            answerMap.put("questionTitle", title);
            answerMap.put("questionCode", MD5Utils.encode(subjectName + title));
            answerMap.put("items", question.getItems());
            answerMap.put("answers", question.getCorrectArray());

            answers.add(answerMap);
        }

        FileUtils.write(new File("d://newAnswerTmp//" + subjectName + ".json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");


        Thread.sleep(2000);
        driver.quit();
    }
}
